//
//  DDOrderDetailsViewController.m
//  Dingdong
//
//  Created by 程强 on 16/12/12.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDOrderDetailsViewController.h"
#import "DDOrderTableCell.h"
#import "DDOrderSectionHeader.h"
#import "DDEvaluateViewController.h"
#import "UIAlertView+Click.h"
#import "DDOrderManager.h"
#import "DDCancelOrderReasonView.h"

@interface DDOrderDetailsViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollHeight;
@property (weak, nonatomic) IBOutlet UITableView *orderTable;
@property (weak, nonatomic) IBOutlet UILabel *receiverNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *receiverPhoneLbl;
@property (weak, nonatomic) IBOutlet UILabel *receiverAddressLbl;
@property (weak, nonatomic) IBOutlet UILabel *orderNoLbl;
@property (weak, nonatomic) IBOutlet UILabel *orderStatusLbl;
@property (weak, nonatomic) IBOutlet UILabel *orderTimeLbl;
@property (weak, nonatomic) IBOutlet UILabel *orderAmountLbl;
@property (weak, nonatomic) IBOutlet UILabel *freightLbl;
@property (weak, nonatomic) IBOutlet UILabel *discountLbl;
@property (weak, nonatomic) IBOutlet UILabel *actualPayLbl;
@property (weak, nonatomic) IBOutlet UILabel *payMethodLbl;
@property (weak, nonatomic) IBOutlet UILabel *distributionTimeLbl;
@property (weak, nonatomic) IBOutlet UILabel *shipTypeLbl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *orderTableBgHeight;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (weak, nonatomic) IBOutlet UIButton *serviceBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIView *botView;
@property (strong, nonatomic) DDOrderManager *manager;

@end

@implementation DDOrderDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDOrderManager new];
    [self layoutDetailsView];
}
- (void)layoutDetailsView
{
    self.scrollWidth.constant = ScreenWidth;
    self.scrollHeight.constant = 1000;
    
    self.botView.layer.shadowOffset = CGSizeMake(0, 2);
    self.botView.layer.shadowOpacity = 0.80;
    self.botView.layer.shadowColor = [UIColor darkGrayColor].CGColor;
    
    kOrderStatus orderStatus = [DDOrderInfo mappingOrderStatus:_order.order.status];
    
    if (orderStatus == kOrderStatusCancel||orderStatus == kOrderStatusComplete) {
        self.deleteBtn.hidden = NO;
        self.deleteBtn.layer.cornerRadius = 3.0;
        self.deleteBtn.layer.borderWidth = 1.0;
    }else{
        self.deleteBtn.hidden = YES;
    }
    
    if (orderStatus == kOrderStatusPending||orderStatus == kOrderStatusConfirm) {
        self.cancelBtn.hidden = NO;
        self.cancelBtn.layer.cornerRadius = 3.0;
        self.cancelBtn.layer.borderWidth = 1.0;
        self.cancelBtn.layer.borderColor = RGBColor(255, 0, 0).CGColor;
    }else{
        self.cancelBtn.hidden = YES;
    }
    
    self.serviceBtn.layer.cornerRadius = 3.0;
    self.serviceBtn.layer.borderWidth = 1.0;
    self.serviceBtn.layer.borderColor = RGBColor(9, 117, 204).CGColor;
    
    self.receiverNameLbl.text = self.order.order.ship_name;
    self.receiverPhoneLbl.text = self.order.order.ship_mobile;
    self.receiverAddressLbl.text = FormatString(@"%@,%@", self.order.order.ship_addr,self.order.order.shipping_area);
    self.orderNoLbl.text = FormatString(@"Order No:%@", self.order.order.sn);
    self.orderStatusLbl.text = FormatString(@"Order Status:%@", self.order.order.orderStatus);
    NSString *time = [ToolKit timeStampTurnDate:FormatString(@"%@", self.order.order.create_time) withFormat:@"yyyy-MM-dd HH:mm:ss"];
    self.orderTimeLbl.text = FormatString(@"Order Time:%@", time);
    self.orderAmountLbl.text = FormatString(@"$%@", self.order.order.goods_amount);
    self.freightLbl.text = FormatString(@"$%@", self.order.order.shipping_amount);
    self.discountLbl.text = FormatString(@"$%@", self.order.order.discount);
    self.actualPayLbl.text = FormatString(@"$%@", self.order.order.needPayMoney);
    self.payMethodLbl.text = self.order.order.payment_name;
    self.distributionTimeLbl.text = FormatString(@"Distribution time:%@", self.order.order.ship_day);
    self.shipTypeLbl.text = @"IBeone";
    
    CGFloat height = 44+self.order.orderItemGoodsList.count*120;
    self.orderTableBgHeight.constant = height;
    self.scrollHeight.constant = 75+10+90+10+height+10+120+10+100+10;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.order.orderItemGoodsList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    DDOrderSectionHeader *header = [[DDOrderSectionHeader alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    if (self.order.orderItemGoodsList.count>0) {
        DDStoreObj *store = self.order.orderItemGoodsList[0].store;
        header.shopName = store.store_name;
    }
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"DetailOrderCell";
    
    DDOrderTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!cell) {
        cell = [[DDOrderTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    DDOrderObjItem *item = self.order.orderItemGoodsList[indexPath.row];
    [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:item.goods.small] placeholderImage:nil];
    cell.goodsNameLbl.text = item.goods.name;
    cell.priceLbl.text = FormatString(@"$%@", item.goods.price);
    cell.countLbl.text = FormatString(@"×%@", item.orderItem.num);

    NSString *addon = item.orderItem.addon;
    NSArray *addAry = [ToolKit JSONDecodeFromString:addon];
    NSString *specString = @"";
    for (NSDictionary *dic in addAry) {
        NSString *key = dic[@"name"];
        NSString *value = dic[@"value"];
        specString = [specString stringByAppendingString:FormatString(@"%@:%@", key,value)];
        specString = [specString stringByAppendingString:@" "];
    }
    cell.goodsSizeLbl.text = specString;

    kOrderStatus orderStatus = [DDOrderInfo mappingOrderStatus:_order.order.status];
    if (orderStatus == kOrderStatusReceived||orderStatus == kOrderStatusComplete) {
        if (item.orderItem.commentState.integerValue == 0) {
            cell.evaluateBtn.hidden = NO;
        }else{
            cell.evaluateBtn.hidden = YES;
        }
    }else{
        cell.evaluateBtn.hidden = YES;
    }
    
    [cell userEvaluateGoods:^{
        DDEvaluateViewController *vc = StoryBoardViewController(@"Evaluate", @"DDEvaluateViewController");
        vc.goods = item.goods;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    return cell;
}

- (IBAction)deleteOrderClick:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Confirm delete the order?" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Delete", nil];
    [alert show];
    weak_Self(self);
    [alert click:^(NSInteger buttonIndex) {
        [self deleteOrderClick:_order.order.order_id success:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
    }];
}
- (IBAction)serviceClick:(id)sender
{
    
}
- (IBAction)cancelClick:(id)sender
{
    //取消订单
    DDCancelOrderReasonView *cancelView = [[DDCancelOrderReasonView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    cancelView.reasonAry = @[@"Do not want to buy now",@"Commodity prices are more expensive",@"Repeat the order",@"Incorrect receipent information"];
    [self.view.window addSubview:cancelView];
    weak_Self(self);
    [cancelView userSelectCancelReason:^(NSString *reason) {
        [self cancelOrderClick:_order.order.order_id reason:reason success:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
    }];

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.clickBlock) {
        alertView.clickBlock(buttonIndex);
    }
}
#pragma mark --- 接口
- (void)cancelOrderClick:(NSNumber *)order_id reason:(NSString *)reason success:(void(^)())block
{
    [[self.manager cancelOrder:order_id reason:reason]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)deleteOrderClick:(NSNumber *)order_id success:(void(^)())block
{
    [[self.manager deleteOrder:order_id]subscribeNext:^(id x) {
        if (block) {
            block();
        }
        [self showMessageHUD:@"Delete success" delayHide:1.0];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        [self showMessageHUD:msg delayHide:1.0];
    } completed:^{
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
